package com.epro.dx.activity.messagecenter;

import java.io.BufferedInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.activity.OrderTrackActivity;
import com.epro.dx.databinding.ActivityMessageCenterBinding;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.task.GetNoticeTypeListAsyncTask;
import com.epro.dx.task.GetNoticesAsyncTask;
import com.epro.dx.task.SetNoticeReadAsyncTask;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.DialogUtils;
import com.epro.dx.util.IntentUtils;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.MessageServiceProvider;
import com.weipu.common.facade.model.MessageModel;
import com.weipu.common.facade.model.NoticeGroupsModel;
import com.weipu.common.observer.MessageObServer;
import com.weipu.common.subject.MessageSubjectImpl;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;
import com.weipu.common.util.NotificationsUtils;
import com.weipu.common.util.StringUtil;

import static android.R.attr.order;


/************************
 * @author Tony
 * @Date:2016-4-6下午5:02:59
 * @描述:消息中心页面
 ************************/
public class MessageCenterActivity extends BaseFragmentActivity implements OnClickListener, MessageObServer {

    //右上角设置按钮
    private RelativeLayout btnSettings;
    //活动消息
    private RelativeLayout eventMessageLayout;
    private ImageView eventMessageImg;
    private TextView eventTime;
    private TextView eventMessageText;
    private TextView eventMessageTitle;
    //系统消息
    private RelativeLayout systemMessageLayout;
    private ImageView systemMessageImg;
    private TextView systemTime;
    private TextView systemMessageText;
    private TextView systemMessageTitle;

    /******************
     * 物流消息 开始
     ****************/
    private RelativeLayout orderMessageLayout;
    private ImageView orderMessageImg;
    private TextView orderMessageText;
    private TextView orderTime;
    private TextView orderMessageTitle;
    private ImageView orderHasNewPoint;

    /******************
     * 物流消息 结束
     ****************/
    //未读消息数量
    private int eventMessageUnreadNumber = 0;
    private int systemMessageUnreadNumber = 0;
    private int orderMessageUnreadNumber = 0;

    //无数据页面
    private RelativeLayout noMessageLayout;

    //未读状态小点
    private ImageView eventHasNewPoint;
    private ImageView systemHasNewPoint;

    private int numberOfUnReadMsg = 0;
    private ActivityMessageCenterBinding binding;
    private DialogUtils build;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendScreen();
        //设置页面及标题部分
        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        setContentView(R.layout.activity_message_center);
        //使用dataBinding的写法
        binding = DataBindingUtil.setContentView(this, R.layout.activity_message_center);
        setLeftBtnContent(true, -1);
        setTitleContent(R.string.page_title_message_center);
        //注册消息观察者
        MessageSubjectImpl.getMessageSubjectImplInstance().attach(this);
        initView();

        //检查系统通知权限是否已经打开了，如果没有打开，且APP的推送开关打开了，则弹窗窗口
        checkSysNotiPermission();
    }

    /**
     * 检查系统权限是否开启
     */
    private void checkSysNotiPermission() {
        String isShow = StringUtil.getConfig("MESSAGE_IS_SHOW", false + "");
        if (!Boolean.parseBoolean(isShow)) {
            if (!NotificationsUtils.isNotificationEnabled(this) && Boolean.parseBoolean(StringUtil.getConfig("IsPush", true + ""))) {

                //弹窗窗口
                showOpenSysDialog();
            }
        }

    }

    /**
     * 提示打开系统权限的弹窗
     */
    private void showOpenSysDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_remark, null);
        build = new DialogUtils.Builder(this)
                .setContentView(view)
                .setEtContent(getResources().getString(R.string.dialog_to_sys_hint))
                .setViewClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.btn_yes) {
                            jumpToAppDetailsSettings();
                        }
                        build.dismiss();
                    }


                }, R.id.btn_yes, R.id.btn_no)
                .build();
        build.showDialog();

        StringUtil.saveConfig("MESSAGE_IS_SHOW",true+"");
    }

    /**
     * 跳转至APP的应用详情页
     */
    private void jumpToAppDetailsSettings() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        IntentUtils.launchActivityByAction(this, Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
    }

    /**
     * @创建：Tony 2016-4-6下午5:06:42
     * @描述：初始化视图控件
     */
    private void initView() {
        btnSettings = (RelativeLayout) findViewById(R.id.message_center_btn_setting);
        btnSettings.setOnClickListener(this);

        //消息根布局
        eventMessageLayout = (RelativeLayout) findViewById(R.id.messages_event_layout);
        systemMessageLayout = (RelativeLayout) findViewById(R.id.messages_system_layout);
        orderMessageLayout = binding.messagesOrderLayout;

        //注册消息根布局点击事件
        eventMessageLayout.setOnClickListener(this);
        systemMessageLayout.setOnClickListener(this);
        orderMessageLayout.setOnClickListener(this);

        //消息的图片
        eventMessageImg = (ImageView) findViewById(R.id.messages_event_img);
        systemMessageImg = (ImageView) findViewById(R.id.messages_system_img);
        orderMessageImg = binding.messagesOrderImg;

        //消息的时间
        eventTime = (TextView) findViewById(R.id.messages_event_time);
        systemTime = (TextView) findViewById(R.id.messages_system_time);
        orderTime = binding.messagesOrderTime;

        //消息的内容
        eventMessageText = (TextView) findViewById(R.id.messages_event_lateast_message);
        systemMessageText = (TextView) findViewById(R.id.messages_system_lateast_message);
        orderMessageText = binding.messagesOrderContent;

        //消息的标题
        eventMessageTitle = (TextView) findViewById(R.id.messages_event_title);
        systemMessageTitle = (TextView) findViewById(R.id.messages_system_title);
        orderMessageTitle = binding.messagesOrderTitle;

        //当没有消息时使用的布局
        noMessageLayout = (RelativeLayout) findViewById(R.id.layout_no_message);

        //未读小红点
        eventHasNewPoint = (ImageView) findViewById(R.id.messages_event_hasnew_point);
        systemHasNewPoint = (ImageView) findViewById(R.id.messages_system_hasnew_point);
        orderHasNewPoint = binding.messagesOrderHasnewPoint;


    }

    @Override
    protected void onResume() {
        //调用接口GetNoticeTypeList获取最新的消息
        getNoticesTypeList();

//        //获取是否还有未读消息，如果还有未读消息，小红点就还在，如果物流消息列表没有未读消息了，小红点消失
//        String hasNoRead = StringUtil.getConfig("HasNoRead", false + "");
//        if (!Boolean.parseBoolean(hasNoRead)) {
//            //如果没有未读消息了
//            orderHasNewPoint.setVisibility(View.GONE);
//        }else {
//            //如果有未读消息
//            orderHasNewPoint.setVisibility(View.VISIBLE);
//
//        }

        super.onResume();
    }

    /**
     * @创建：Tony 2016-5-5下午2:05:57
     * @描述：获取最新消息状态
     */
    private void getNoticesTypeList() {
        AsyncTaskUtil.executeTask(new GetNoticeTypeListAsyncTask(MessageCenterActivity.this, new MyAsyncTaskListenner() {

            @Override
            public void onPreTask() {
                showLoadingLayout(null);
            }

            @SuppressWarnings("unchecked")
            @Override
            public void onPostTask(String result, Object obj) {
                if (!isFinishing()) {
                    hideAllLayout();
                    if ("0".equals(result)) {
                        refreshUI((ArrayList<NoticeGroupsModel>) obj);
                    } else {
                        AlertToast.alert(MessageCenterActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                    }
                }
            }
        }));
    }

    /**
     * @param model
     * @创建：Tony 2016-5-4下午3:04:54
     * @描述：更新页面显示
     */
    protected void refreshUI(ArrayList<NoticeGroupsModel> modelList) {
        if (null != modelList && modelList.size() > 0) {
            noMessageLayout.setVisibility(View.GONE);
            systemMessageLayout.setVisibility(View.GONE);
            eventMessageLayout.setVisibility(View.GONE);

            for (int i = 0; i < modelList.size(); i++) {
                NoticeGroupsModel noticeGroupsModel = modelList.get(i);
                MessageModel messageModel = noticeGroupsModel.getNotcie();
                switch (noticeGroupsModel.getNoticeType()) {
                    case MessageModel.NOTICETYPE_SYSTEM:
                        //系统消息
                        systemMessageLayout.setVisibility(View.VISIBLE);
                        if (noticeGroupsModel.getUnReadCount() > 0) {
                            systemHasNewPoint.setVisibility(View.VISIBLE);
                        } else {
                            systemHasNewPoint.setVisibility(View.GONE);
                        }
                        systemMessageUnreadNumber = noticeGroupsModel.getUnReadCount();
                        if (null != messageModel) {
                            systemMessageText.setText(messageModel.getContent());
                            systemMessageTitle.setText(messageModel.getTitle());
                            //设置时间显示
//						systemTime.setText(formatTime(messageModel.getCreateAt()));
                            systemTime.setText(formatTimeToLocal(messageModel.getCreateAt()));
                        }
                        break;
                    case MessageModel.NOTICETYPE_EVENT:
                        //活动消息
                        eventMessageLayout.setVisibility(View.VISIBLE);
                        if (noticeGroupsModel.getUnReadCount() > 0) {
                            eventHasNewPoint.setVisibility(View.VISIBLE);
                        } else {
                            eventHasNewPoint.setVisibility(View.GONE);
                        }
                        eventMessageUnreadNumber = noticeGroupsModel.getUnReadCount();
                        if (null != messageModel) {
                            eventMessageText.setText(messageModel.getContent());
                            eventMessageTitle.setText(messageModel.getTitle());
                            //设置时间显示
                            eventTime.setText(formatTimeToLocal(messageModel.getCreateAt()));
                        }
                        break;

                    case MessageModel.NOTICETYPE_ORDER:
                        //物流消息
                        orderMessageLayout.setVisibility(View.VISIBLE);
                        if (noticeGroupsModel.getUnReadCount() > 0) {
                            //如果未读消息数量大于0，则显示小红点
                            orderHasNewPoint.setVisibility(View.VISIBLE);
                        } else {
                            //如果没有未读消息，则隐藏小红点
                            orderHasNewPoint.setVisibility(View.GONE);
                        }
                        orderMessageUnreadNumber = noticeGroupsModel.getUnReadCount();
                        if (null != messageModel) {
                            String content = messageModel.getTitle();
                            //由于后台返回的内容信息和需求不一致，所以自己拆分字符串进行组装
                            String[] contentSplit = content.split("\\r\\n");
                            //设置status
                            if (contentSplit.length > 1 && content.contains("Status")) {

                                orderMessageText.setText(contentSplit[1]);
                            }

                            //设置消息的标题，后台返回的数据标题是放在Content字段的
                            orderMessageTitle.setText(messageModel.getContent());
                            //设置时间显示,格式化为当地的时间
                            orderTime.setText(formatTimeToLocal(messageModel.getCreateAt()));
                        }
                        break;

                    default:
                        break;
                }
            }
            numberOfUnReadMsg = eventMessageUnreadNumber + systemMessageUnreadNumber + orderMessageUnreadNumber;

        } else {
            //显示空数据页面
            noMessageLayout.setVisibility(View.VISIBLE);
        }
        if (0 == numberOfUnReadMsg) {
            refreshMessageUnreadNumber(0);
        }
    }

    /**
     * @param createAt
     * @return
     * @创建：Tony 2016-5-6下午4:53:16
     * @描述：根据本地时区格式化显示发信时间
     */
    private CharSequence formatTimeToLocal(String createAt) {
        SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone pst = TimeZone.getTimeZone("Etc/GMT+0");
        try {
            localDateFormat.setTimeZone(pst);
            Date oldDate = localDateFormat.parse(createAt);
            localDateFormat.setTimeZone(TimeZone.getDefault());
            String oldDateText = localDateFormat.format(oldDate);
            Date newDate = new Date(System.currentTimeMillis());
            String newDateText = localDateFormat.format(newDate);
            String[] splitOldDate = oldDateText.split(" ");
            String[] splitNewDate = newDateText.split(" ");
            if ((splitNewDate[0]).equals(splitOldDate[0])) {
                //今天的消息，显示时间
                String[] timeSplit = splitOldDate[1].split(":");
                return timeSplit[0] + ":" + timeSplit[1];
            } else {
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(newDate);
                calendar.add(Calendar.DATE, -1);//把日期往前减一天.整数往后推,负数往前移动
                String yesterday = localDateFormat.format(calendar.getTime());//昨天的日期
                yesterday = yesterday.split(" ")[0];
                if (yesterday.equals(splitOldDate[0])) {
                    return getString(R.string.yesterday);
                } else {
                    return splitOldDate[0];

                }
            }
        } catch (ParseException e) {
            return null;
        }
    }


    @Override
    public void onDestroy() {
        //移除消息观察者
        MessageSubjectImpl.getMessageSubjectImplInstance().remove(this);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.message_center_btn_setting:
                sendGAEvent("点击消息中心设置按钮");
                Intent intent = new Intent(MessageCenterActivity.this, MessageCenterSettingsActivity.class);
                startActivity(intent);
                break;
            case R.id.messages_event_layout://活动消息
                sendGAEvent("点击进入活动消息列表");
                gotoListPage(MessageModel.NOTICETYPE_EVENT);
                refreshMessageUnreadNumber(eventMessageUnreadNumber);
                break;
            case R.id.messages_system_layout://系统消息
                sendGAEvent("点击进入系统消息列表");
                gotoListPage(MessageModel.NOTICETYPE_SYSTEM);
                refreshMessageUnreadNumber(systemMessageUnreadNumber);
                break;

            case R.id.messages_order_layout://物流消息
                sendGAEvent("点击进入物流消息列表");
//                gotoListPage(MessageModel.NOTICETYPE_ORDER);
                gotoOrderListPage(MessageModel.NOTICETYPE_ORDER);
//                refreshMessageUnreadNumber(orderMessageUnreadNumber);
                break;

            default:
                break;
        }
    }

    /**
     * 请求网络，完毕跳转至物流消息列表（因为这个列表和上版本的其他列表样式不一致，无法共用一个页面，所以另起一个页面）
     *
     * @param noticetype 消息的类型
     */
    private void gotoOrderListPage(final int noticetype) {
        AsyncTaskUtil.executeTask(new GetNoticesAsyncTask(MessageCenterActivity.this, noticetype, 1, Constant.LIST_PAGE_COUNT, new MyAsyncTaskListenner() {

            @Override
            public void onPreTask() {
                showLoadingLayout(null);
            }

            @Override
            public void onPostTask(String result, Object obj) {
                if (!isFinishing()) {
                    hideAllLayout();
                    if ("0".equals(result)) {
                        //设置已读
//                        AsyncTaskUtil.executeTask(new SetNoticeReadAsyncTask(MessageCenterActivity.this, noticetype == MessageModel.NOTICETYPE_EVENT ?
//                                MessageServiceProvider.ACTIONTYPE_ACTIVE_ALL : MessageServiceProvider.ACTIONTYPE_SYSTEM_ALL, null, null));
                        //跳转列表页面
                        Bundle bundle = new Bundle();
                        ArrayList<MessageModel> modelList = (ArrayList<MessageModel>) obj;
                        Intent intent = new Intent(MessageCenterActivity.this, OrderTrackActivity.class);
                        bundle.putParcelableArrayList("MessageList", modelList);
                        intent.putExtra(ServerConstant.MessageCenter.INTENT_BUNDLE, bundle);
                        startActivity(intent);
                    } else {
                        AlertToast.alert(MessageCenterActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                    }
                }
            }
        }));
    }

    /**
     * @param eventMessageUnreadNumber2
     * @创建：Tony 2016-5-5下午2:14:10
     * @描述：修改未读消息数量
     */
    private void refreshMessageUnreadNumber(int readNumber) {
        numberOfUnReadMsg -= readNumber;
        if (numberOfUnReadMsg <= 0) {
            StringUtil.saveConfig(ServerConstant.MessageCenter.UNREAD_MESSAGE, String.valueOf(false));
            StringUtil.saveConfig(ServerConstant.MessageCenter.UNREAD_MESSAGE_COUNT, String.valueOf(0));
        }
    }

    /**
     * @param noticetypeEvent
     * @创建：Tony 2016-5-4下午4:15:30
     * @描述：跳转到消息列表页面
     */
    private void gotoListPage(final int noticetType) {
        AsyncTaskUtil.executeTask(new GetNoticesAsyncTask(MessageCenterActivity.this, noticetType, 1, Constant.LIST_PAGE_COUNT, new MyAsyncTaskListenner() {

            @Override
            public void onPreTask() {
                showLoadingLayout(null);
            }

            @Override
            public void onPostTask(String result, Object obj) {
                if (!isFinishing()) {
                    hideAllLayout();
                    if ("0".equals(result)) {
                        //设置已读
                        AsyncTaskUtil.executeTask(new SetNoticeReadAsyncTask(MessageCenterActivity.this, noticetType == MessageModel.NOTICETYPE_EVENT ?
                                MessageServiceProvider.ACTIONTYPE_ACTIVE_ALL : MessageServiceProvider.ACTIONTYPE_SYSTEM_ALL, null, null));
                        //跳转列表页面
                        Bundle bundle = new Bundle();
                        ArrayList<MessageModel> modelList = (ArrayList<MessageModel>) obj;
                        Intent intent = new Intent(MessageCenterActivity.this, MessagesAndPromotionsListActivity.class);
                        bundle.putBoolean(ServerConstant.MessageCenter.ISPROMOTION, MessageModel.NOTICETYPE_EVENT == noticetType ? true : false);
                        //设置列表页的标题
                        bundle.putInt(ServerConstant.PAGETITLEID,
                                MessageModel.NOTICETYPE_EVENT == noticetType ? R.string.messages_event_title :
                                        MessageModel.NOTICETYPE_SYSTEM == noticetType ? R.string.messages_system_title : R.string.messages_order_title);
                        //设置是从Message Center页面跳转到列表页的 ，因为还可以是从首页跳转过来的，这是加个标记区分
                        bundle.putInt(MessagesAndPromotionsListActivity.FROMTYPE, MessagesAndPromotionsListActivity.FROMTYPE_MESSAGECENTER);
                        bundle.putParcelableArrayList("MessageList", modelList);
                        intent.putExtra(ServerConstant.MessageCenter.INTENT_BUNDLE, bundle);
                        startActivity(intent);
                    } else {
                        AlertToast.alert(MessageCenterActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                    }
                }
            }
        }));
    }

    @Override
    public void notifyMessageChange(int newMsgNum, int msgType) {
        //消息变化时 刷新小红点
        getNoticesTypeList();
    }
}
